package com.telecom.sxint.app.core.service.impl.Pictureimpl;

import cn.zjtele.pubinfo.common.http.request.RequestContext;
import cn.zjtele.pubinfo.common.http.request.RequestContextHolder;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.telecom.sxint.app.core.domain.entity.Picturepojo.App1Picturemanagement;
import com.telecom.sxint.app.core.domain.entity.Picturepojo.App1Pictureuser;
import com.telecom.sxint.app.core.domain.entity.dto.App1PictureuserDTO;
import com.telecom.sxint.app.core.mapper.Picturemapper.App1PicturemanagementMapper;
import com.telecom.sxint.app.core.mapper.Picturemapper.App1PictureuserMapper;
import com.telecom.sxint.app.core.service.Pictureservice.IApp1PicturemanagementService;
import com.telecom.sxint.app.core.service.Pictureservice.IApp1PictureuserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Service
public class App1PictureuserServiceImpl  extends ServiceImpl<App1PictureuserMapper, App1Pictureuser> implements IApp1PictureuserService {
    @Autowired
    private App1PictureuserMapper app1PictureuserMapper;
    @Autowired
    private IApp1PicturemanagementService iApp1PicturemanagementService;
    @Autowired
    private App1PicturemanagementMapper app1PicturemanagementMapper;
    /**
     * 用户点击下载(未下载过新增，下载过增加下载次数)
     * @param app1PictureuserDTO
     * @return
     */
    @Override
    @Transactional
    public ResponseData insertUserPicture(Integer pictureid, App1PictureuserDTO app1PictureuserDTO, HttpServletResponse response) throws UnsupportedEncodingException {
        /**
         * 网络连接获取图片
         */
        // 查询该id是否有该实体
        App1Picturemanagement app1Picturemanagement = app1PicturemanagementMapper.selectById(pictureid);

        if (app1Picturemanagement == null) {
            return ResponseData.failed("没有该id实体信息", "41007");
        }
        // 获取文件路径
        String mediaPath = app1Picturemanagement.getLink();

        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(mediaPath);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return ResponseData.failed("没有图片或视频链接", "41007");
            }

            // 设置响应头
            response.setContentType(connection.getContentType());
            String fileName = URLEncoder.encode(url.getPath().substring(url.getPath().lastIndexOf('/') + 1), "UTF-8").replaceAll("\\+", "%20");
            ContentDisposition contentDisposition = ContentDisposition.attachment()
                    .filename(fileName, java.nio.charset.StandardCharsets.UTF_8)
                    .build();
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());

            try (InputStream in = connection.getInputStream();
                 OutputStream out = response.getOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件传输过程中发生错误");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ResponseData.failed("无效的URL", "41008");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseData.failed("打开链接时发生错误", "41009");
        }

        // 增加下载次数
        Integer downloadCount = app1Picturemanagement.getDownloadCount() + 1;
        UpdateWrapper<App1Picturemanagement> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", pictureid).set("download_count", downloadCount);
        app1PicturemanagementMapper.update(null, updateWrapper);
//        iApp1PicturemanagementService.updateDownload(pictureid,response);
        App1Picturemanagement app1Picturemanagement1 = app1PicturemanagementMapper.selectById(pictureid);
        QueryWrapper<App1Pictureuser> app1PictureuserQueryWrapper = new QueryWrapper<>();
        app1PictureuserQueryWrapper
                .eq("link",app1Picturemanagement1.getLink())
                .eq("token_name",app1PictureuserDTO.getTokenName());
        App1Pictureuser one = app1PictureuserMapper.selectOne(app1PictureuserQueryWrapper);
        System.out.println(one);
        //不存在则插入
        if(one==null){
            App1Pictureuser app1Pictureuser3 = new App1Pictureuser();
            BeanUtils.copyProperties(app1PictureuserDTO,app1Pictureuser3);
            app1Pictureuser3.setLink(app1Picturemanagement.getLink());
            app1Pictureuser3.setDownloadCount(1);
//            app1Pictureuser3.setTokenName(context.getUserName());
//            app1Pictureuser3.setIsAdmin(superAdmin);
            app1PictureuserMapper.insert(app1Pictureuser3);
        }
        else {

            //存在则增加下载次数
            App1Pictureuser app1Pictureuser2 = app1PictureuserMapper.selectById(one.getId());
            System.out.println("app1Pictureuser2"+"----"+app1Pictureuser2);
            // 增加下载次数
            Integer downloadCount2 = app1Pictureuser2.getDownloadCount() + 1;
            System.out.println("downloadCount"+"**"+downloadCount2);
            UpdateWrapper<App1Pictureuser> updateWrapper2 = new UpdateWrapper<>();
            updateWrapper2.eq("id", one.getId()).set("download_count", downloadCount2);
            app1PictureuserMapper.update(null, updateWrapper2);
        }
        return null;
    }



    /**
     * 返回该用户的总下载次数
     * @param tokenName
     * @return
     */
    @Override
    public List<Map<String, Object>> userAllDownload(String tokenName) {
        QueryWrapper<App1Pictureuser> wrapper = new QueryWrapper<>();
        wrapper.groupBy("token_name");
        wrapper.
                select("token_name", "sum(download_count) allcount")
                .eq("token_name",tokenName);
        List<Map<String, Object>> maps = app1PictureuserMapper.selectMaps(wrapper);

        return maps;
    }


}